package nl.hu.verbrandendephoenix.client;

import nl.hu.verbrandendephoenix.controller.AddAuction;
import nl.hu.verbrandendephoenix.controller.BlockUser;
import nl.hu.verbrandendephoenix.controller.BuyCredits;
import nl.hu.verbrandendephoenix.controller.EditProfile;
import nl.hu.verbrandendephoenix.controller.Inbox;
import nl.hu.verbrandendephoenix.controller.MyAuctions;
import nl.hu.verbrandendephoenix.controller.OpenConversation;
import nl.hu.verbrandendephoenix.controller.Register;
import nl.hu.verbrandendephoenix.controller.SearchAuction;
import nl.hu.verbrandendephoenix.controller.SearchUser;
import nl.hu.verbrandendephoenix.controller.Statistics;
import nl.hu.verbrandendephoenix.controller.TopAuctions;
import nl.hu.verbrandendephoenix.controller.ViewAuction;
import nl.hu.verbrandendephoenix.view.Home;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;

public class HistoryListener {

	private RootPanel pnlContent;
	final NotificationManager nM = NotificationManager.get();
	private boolean isLoggedIn = false;

	public HistoryListener(RootPanel pnlContent) {
		this.pnlContent = pnlContent;
		String initToken = History.getToken();
		if(initToken.length() == 0) {
			historyChanged("searchauction");
		} else {
			historyChanged(initToken);
		}
		TheListener();
	}
	/*
	 * HistoryListener checkt de link (#foo) en wanneer dit een bekende pagina is, laad hij deze.
	 */

	public HistoryListener() {}

	private void TheListener() {
		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				String token = History.getToken();
				historyChanged(token);				
			}
		});
	}

	private void historyChanged(final String token) {
		if(Cookies.getCookie("loginString") == null ||Cookies.getCookie("loginString").length() < 1) {
			isLoggedIn = false;
			historyTokens(token);
		} else {
			AppManager.get().getRpcService().validLogin(Cookies.getCookie("loginString"), new AsyncCallback<Boolean>() {
				public void onFailure(Throwable caught) {
					nM.commError();
					isLoggedIn = false;
					historyTokens(token);
				}
				public void onSuccess(Boolean result) {
					isLoggedIn = result;
					historyTokens(token);
				}
			});
		}
	}
	private void historyTokens(String token) {
		if(token.equals("register")) {
			if(isLoggedIn) {
				History.newItem("editprofile");
			}
			else {
				changePage(new Register(pnlContent).getPanel());
			}
		} else if(token.equals("editprofile")) {
			if(isLoggedIn) {
				EditProfile eP = new EditProfile();
				Panel p = eP.getPanel();
				changePage(p);
				eP.getData();
			} else {
				notLoggedIn();
			}

		} else if (token.length() > 12 && token.substring(0,11).equals("editprofile")) { 
			if(isLoggedIn) {
				try {
					String tokenarr[] = token.split("-");
					EditProfile eP = new EditProfile();
					Panel p = eP.getPanel();
					changePage(p);
					eP.getData(tokenarr[1]);
				} 
				catch(Exception e) { e.printStackTrace(); }
			} else {
				notLoggedIn();
			}
		} else if (token.length() > 12 && token.substring(0,9).equals("blockuser")) { 
			if(isLoggedIn) {
				try {
					String tokenarr[] = token.split("-");
					changePage(new BlockUser(tokenarr[1]).getPanel());
				} catch(Exception e) { e.printStackTrace(); }
			}
			else {
				notLoggedIn();
			}
		} else if(token.equals("searchuser")) {
			changePage(new SearchUser().getPanel());
		} else if(token.equals("new_auction")) {
			if(isLoggedIn) {
				changePage(new AddAuction().getPanel());
			}
			else {
				notLoggedIn();
			}
		} else if(token.equals("myAuctions")){
			if(isLoggedIn) {
				changePage(new MyAuctions().getPanel());
			}
			else {
				notLoggedIn();
			}
		} else if(token.equals("searchauction")) {
			changePage(new SearchAuction().getPanel());
		} else if (token.length() > 12 && token.substring(0,11).equals("viewauction")) { 
			try {
				String tokenarr[] = token.split("-");
				ViewAuction vA = new ViewAuction();
				Panel p = vA.getPanel(Integer.parseInt(tokenarr[1]));
				changePage(p);
			} catch(Exception e) { e.printStackTrace(); }
		} else if(token.equals("buyCredits")){
			if(isLoggedIn) {
				changePage(new BuyCredits().getPanel());
			}
			else {
				notLoggedIn();
			}
		} else if(token.equals("inbox")){
			if(isLoggedIn) {
				changePage(new Inbox().getPanel());
			} else {
				notLoggedIn();
			}
		} else if(token.equals("topauctions")) {
			new TopAuctions().getPanel();
		} else if(token.equals("statistics")) {
			changePage(new Statistics().getPanel());
		} else if(token.equals("home")) {
			changePage(new Home().getHome());
		} else if (token.length() > 13 && token.substring(0,12).equals("conversation")) { 
			try {
				String tokenarr[] = token.split("_");
				OpenConversation oC = new OpenConversation();
				Panel p = oC.getPanel(Integer.parseInt(tokenarr[1]));
				changePage(p);
			} catch(Exception e) { e.printStackTrace(); }
		} else {
			changePage(new SearchAuction().getPanel());
		}
	}
	/* Voor als de #tag veranderd is */

	private void changePage(Panel newPage) {
		pnlContent.clear();
		pnlContent.add(newPage);
	}
	/* De webcontent veranderen (pagina veranderen in zekere zin), aanroep vanuit historyChanged */

	private void notLoggedIn() {
		pnlContent.clear();
		pnlContent.add(new Label("U bent niet ingelogd. Gelieve in te loggen via het menu linksonder."));
		pnlContent.add(new Anchor("Registreer", "#register"));
	}
	/* notLoggedIn() Genereerd content wanneer je een pagina probeert te bekijken vwaarvoor je
	 * ingelogd moet zijn.
	 */

	/* 
	 * Refresh de huidige pagina, bijv na inloggen.
	 */
	public void refresh() {
		String token = History.getToken();
		historyChanged(token);
	}
}
